package me.henrydhc.naiveeconomy.task;

import java.sql.SQLException;
import java.util.List;

import org.bukkit.scheduler.BukkitRunnable;

import me.henrydhc.naiveeconomy.account.EcoAccount;
import me.henrydhc.naiveeconomy.cache.AccountCache;
import me.henrydhc.naiveeconomy.cache.EnergeticCache;
import me.henrydhc.naiveeconomy.cache.LazyAccountCache;
import me.henrydhc.naiveeconomy.connector.Connector;

public class CacheSaveTask extends BukkitRunnable {

    private final Connector connector;
    private final AccountCache cache;

    public CacheSaveTask(Connector connector, AccountCache cache) {
        this.connector = connector;
        this.cache = cache;
    }

    @Override
    public void run() {
        
        if (cache instanceof LazyAccountCache) {
            saveLazyCache();
        } else {
            saveEnergeticCache();
        }

    }

    private void saveEnergeticCache() {
        EnergeticCache energeticCache = (EnergeticCache)this.cache;
        List<EcoAccount> accounts = energeticCache.getAllAccountCopy();

        for (EcoAccount account: accounts) {
            try {
                connector.saveAccount(account);
            } catch (SQLException e) {
                e.printStackTrace();
                return;
            }
        }
        energeticCache.clearCache();
    }

    private void saveLazyCache() {
        while (true) {

            EcoAccount account = cache.removeOldestAccount();
            if (account == null) {
                return;
            }

            try {
                connector.saveAccount(account);
            } catch (SQLException e) {
                e.printStackTrace();
                return;
            }

        }
    }
}
